<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>

      <!-- 放置table组件 -->
      <el-table :data="rolesList">
        <!-- 放置列 -->
        <el-table-column align="center" label="序号" width="300" prop="id" />
        <el-table-column align="center" label="角色" width="300">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="启用" width="200">
          <!-- v-slot="{row}" 与  #default="{ row }"  效果是一样的 -->
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-switch v-model="row.editRow.state" :active-value="1" :inactive-value="0" size="mini" />
            </template>
            <template v-else>
              <span>  {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
            </template>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" width="300">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300">
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="onEdit(row)">确认</el-button>
              <el-button size="mini" type="danger" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <!-- 气泡弹层 -->
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>
      </el-table>

      <!-- 放置分页组件 -->
      <el-row type="flex" style="height: 60px;" align="middle" justify="center">
        <el-pagination :page-size="pageParams.pagesize" :current-page="pageParams.page" :total="pageParams.total" layout="prev, pager, next" @current-change="changePage" />
      </el-row>
    </div>
    <!-- 放置添加角色对话框弹层 -->
    <el-dialog title="添加角色" width="500px" :visible.sync="showDialog" @close="btnCancel">
      <!-- 表单 -->
      <el-form ref="roleFormRef" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
          <el-button size="mini" @click="btnCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree
        ref="permTree"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>

  </div>

</template>

<script>
import { getPermissionListApi } from '@/api/permission'
import { getRoleListApi, addRoleApi, delRoleApi, updateRoleApi, getRoleDetailApi, assignPermApi } from '@/api/role'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      rolesList: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      // 控制分配权限弹层
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleListApi(this.pageParams)
      this.rolesList = rows
      this.pageParams.total = total
      // 给数据数组中每一个对象添加一个isEdit属性
      this.rolesList.forEach(item => {
        this.$set(item, 'isEdit', false)
        // 给数组添加一个对象，用于回显
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    // 切换分页时 请求新的数据
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    async btnOK() {
      // 1. 整体校验
      await this.$refs.roleFormRef.validate()
      await addRoleApi(this.roleForm)
      this.$message.success('添加角色成功')
      this.getRoleList()
      this.btnCancel()
    },
    btnCancel() {
      // 1. 重置表单
      this.$refs.roleFormRef.resetFields()
      // 2. 关闭弹层
      this.showDialog = false
    },
    async  confirmDel(id) {
      await delRoleApi(id)
      // 最后一页, 最后一条数据
      if (this.rolesList.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page -= 1
      }
      this.$message.success('删除角色成功')
      this.getRoleList()
    },
    // 编辑行内数据
    btnEditRow(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
    },
    // 编辑行内数据
    async onEdit(row) {
      if (!row.editRow.name || !row.editRow.state) {
        this.$message.warning('角色名称和描述不能为空~')
        return
      }
      await updateRoleApi({
        id: row.id,
        ...row.editRow
      })
      this.$message.success('修改角色成功')
      Object.assign(row, {
        isEdit: false,
        ...row.editRow
      })
    },
    async  btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetailApi(id)
      this.permIds = permIds
      this.permissionData = transListToTreeData(await getPermissionListApi(), 0)
      this.showPermissionDialog = true
    },
    // 点击确定时触发
    async  btnPermissionOK() {
      await assignPermApi({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
  .role-operate {
  padding: 10px;
}
</style>
